// 床位费类型与费用项目关联界面
import React from 'react';
import { Select, Row, Col, Button, Spin, Divider, Popconfirm, message, Icon } from 'antd';
import { $http } from '../../containers/config/https';
import store from 'store';
import PubilcTablePagination from '../common/PubilcTablePagination.jsx'; // 公共table组件
import CommonLibraryImport from './common/CommonLibraryImport.jsx'; // 	公共库导入
import 'assets/css/common.css'

const { Option } = Select;
let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};

export default class DepartmentInformation extends React.Component {

	constructor({ history }) {
		super();
		this.history = history;
		this.state = {
			// 所属医院
			hospitalId: undefined,
			// 科室名称
			locDesc: undefined,
			// 记录状态
			status: undefined,
			// 科室类型
			locType: undefined, 
			// 表格数据
			tableData: [],
			// 表格数据总条数
			total: 0,
			showLoading: true,
			page: 1,
			pageSize: 10,
			selectData: {}, // 科室信息下拉框数据
			DepartmentInformation: [], // 科室名称下拉框
			hospitalData: [], // 所属医院
			headerHeight: 0,
			loading: false
		};
		this.columns = [
			{
			  key: 1,
			  title: '医院',
			  dataIndex: 'hospDescripts',
				align: "center",
				width: '10%'
			},
			{
			  key: 2,
			  title: '床位费类型',
			  dataIndex: 'bedFeeTypeDescripts',
				align: "center",
				width: '12%'
			},
			{
			  key: 3,
			  title: '费用项目',
			  dataIndex: 'medItemDescripts',
				align: "center",
				width: '10%',
            },
            {
                key: 4,
                title: '生效日期',
                dataIndex: 'startDate',
                  align: "center",
                  width: '10%',
              },
              {
                key: 5,
                title: '失效日期',
                dataIndex: 'stopDate',
                  align: "center",
                  width: '10%',
              },
              {
                key: 6,
                title: '创建日期',
                dataIndex: 'createDate',
                  align: "center",
                  width: '10%',
              },
              {
                key: 7,
                title: '创建人员',
                dataIndex: 'createUserDescripts',
                  align: "center",
                  width: '10%',
              },
			{
			  title: '操作',
			  key: 10,
			  align: "center",
			  width: 130,
			  render: (text, record) => (
				<span>
					<Icon type="edit" style={{color: '#108EE9'}}></Icon>
				  <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
				  {/* 分割线 */}
				  <Divider type="vertical" />
					<Icon type="delete" style={{color: 'rgba(240,65,52,1)'}}></Icon>
				  <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
						<span className='span' style={{color: 'rgba(240,65,52,1)'}}>删除</span>
				  </Popconfirm>
				</span>
			  ),
			}
		]
	}

	componentDidMount() {
		this.initData();
		// console.log(store.getState().tableHeight.y)
	}

	componentWillUnmount() {
		// 组件销毁前将静止让setState修改state的状态
        this.setState = (state,callback)=>{ return; }
	}

	initData() {
		// 初始化下拉框数据
		this.getSelectData();
		this.loadHospitalMsg()
		// 组件加载完毕关闭loading
		this.setState({ showLoading: false });
		// 初始化列表数据
		this.handleQuery();
		var box = document.querySelector(".department-header");
		if(box){ //此处在加一层判断，更加严密，如果box存在的情况下获取
			this.setState({headerHeight: box.offsetHeight})
		}
	}

	// 获取下拉框数据
	getSelectData() {
		let data = {
			params: [
				{
				
				}
			]
		}
		$http.post('urlS', this, {
			code: "01040009",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({ selectData: res })
				} else {
					this.setState({ selectData: {} })
				}
			}
		})
	}

	// 3.13.23.获取科室信息
	getDepartmentInformation(id) {
		if (id) {
			let data = {
				params: [
					{ hospID: id}
				]
			}
			$http.post('urlS', this, {
				code: "04020008",
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						this.setState({ DepartmentInformation: res.result.Data})
					} else {
						this.setState({ DepartmentInformation: [] })
					}
				}
			})
		} else {
			this.setState({ DepartmentInformation: [] })
		}
	}

	// 调用公共组件的连接事件
	onRef = (ref) => {
		this.child = ref
	}

	// 调用子组件公共库导入的连接事件
	libraryOnRef = (ref) => {
		this.libraryChild = ref
	}

	onFocusLocDesc = () => {
		if (this.state.hospitalId === undefined) {
			message.info("请先选择所属医院");
		}
	}

	// 查询条件 --- 所属医院
	onChangehospitalId = (e) => {
		// console.log(e.target.value)
		this.setState({ hospitalId: e, locDesc: undefined }, () => {
			this.getDepartmentInformation(e)
		});
	}

	// 查询条件 --- 科室名称
	onChangeLocDesc = (e) => {
		this.setState({ locDesc: e });
	}

	// 查询条件 --- 科室类型
	onChangelocType = (e) => {
		this.setState({ locType: e });
	}

	// 查询条件 --- 记录状态
	onChangeStatus = (e) => {
		this.setState({ status: e });
	}

	// 提供修改page和pageSize的回调函数
	compilePage(page, pageSize) {
		// 修改page，或者pageSize
		this.setState({ page: page, pageSize: pageSize }, () => {
			// 重新调用查询方法
			let { status, hospitalId, locDesc, locType } = this.state;
			this.getTableData(status, hospitalId, locDesc, locType)
		})
	}

	// 请求列表数据
	getTableData (status, hospitalId, locDesc, locType) {
		this.setState({loading: true})
		let {page, pageSize} = this.state;
		let data = {
			params: [{
				hospId: "", // 所属医院
				bedFeeTypeId: locDesc, // 科室名称
				medItemId: status, // 记录状态
				startDate: "",
				stopDate: ""
			}],
			pagination: [{
				pageSize: pageSize,
				currentPage: page
			}]
		}
		$http.post('urlS', this, {
			code: "01040141",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0 && res.result) {
					this.setState({ tableData: res.result.data, total: res.result.TotalCount, loading: false })
					// 数据加载成功关闭loading
					this.child.handleLoading();
				} else {
					this.setState({ tableData: [], total: 0, loading: false })
					// 数据加载失败关闭loading
					this.child.handleLoading();
				}
			},
			error: function (error) {
				this.setState({ tableData: [], total: 0, loading: false}, () => {
					// 数据加载成功关闭loading
					this.child.handleLoading();
				})
			}
		})
	}

	//获取所属医院
	loadHospitalMsg() {
		var data = {
			params: [{
				hospID: '', // 医院id
				logonGroupID: user&&user.groupID ? user.groupID : '', //登录角色id
				logonHospID: user&&user.hospID ? user.hospID : '', // 登录医院id
			}]
		}
		$http.post('urlS', this, {
			code: "01040001",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({
						hospitalData: res.depDoctor,
						// hospitalId: res.depDoctor ? res.depDoctor[0].id : undefined
					})
					var result = res.depDoctor && res.depDoctor.some(item => {
						if (item.id === user.hospID) {
								return true
						}
					})
					if (!result) {
						this.setState({
								hospitalId: undefined
						})
					} else {
						this.setState({hospitalId: user.hospID ? user.hospID : undefined})
						this.getDepartmentInformation(user.hospID)
					}
				}
			}
		});
	}

	// 查询
	handleQuery = () => {
		this.setState({ page: 1, pageSize: 10 }, () => {
			let { status, hospitalId, locDesc, locType } = this.state;
			this.getTableData(status, hospitalId, locDesc, locType)
		})
	}

	// 点击公共库导入显示弹框
	handleLibraryImport = () => {
		this.libraryChild.showModal();
	}

	// 新增科室跳转到新增界面
	handleAdd = () => {
		// 点击跳转导航栏新加新增角色
		this.props.openWindowBySubTab({
			title: '新增科室',
			path: '/6002/001',
			Paras: {
				targetKey: '新增科室',
				flag: 'add',
			},
			component: "pages/departmentInformation/NewDepartment.jsx"
		});
	}

	// 编辑
	handleCompile = (record) => {
		this.props.openWindowBySubTab({
			title: '编辑科室',
			path: '/6002/001',
			Paras: {
				targetKey: '编辑科室',
				flag: 'compile',
				userInfo: record
			},
			component: "pages/departmentInformation/NewDepartment.jsx"
		});
	}

	// 删除
	handleDelete = (record) => {
		let data = {
			params: [{
				locID: record.locID,
				updateUserID: user&&user.userID ? user.userID : ''
			}]
		}
		$http.post('urlADS', this, {
			code: '01050005',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					message.success('操作成功：状态值已变更成失效');
					// 刷新列表数据
					let { status, hospitalId, locDesc, locType } = this.state;
					this.getTableData(status, hospitalId, locDesc, locType)
				}
			}
		})
	}

	render() {
		// 组件所需参数
		const param = {
			// 表头配置
			columns: this.columns,
			// 表格数据
			data: this.state.tableData,
			// 数据总条数
			total: this.state.total,
			// 当前页数
			page: this.state.page,
			loading: this.state.loading,
			// 表格的宽度
			x: 900,
			y: store.getState().tableHeight.y + 78 - this.state.headerHeight,
			height: store.getState().tableHeight.y + 123 - this.state.headerHeight + 'px',
		}
		return (
			<Spin tip="加载中..." spinning={this.state.showLoading} className="department">
				<div>
					<div className="department-header">
						<Row style={{ minHeight: '64px', padding: '0 24px' }}>
							<Col span={18}>
								所属医院：<Select showSearch optionFilterProp="seatchprop" allowClear value={this.state.hospitalId} onChange={this.onChangehospitalId} style={{width: '150px', margin: '23px 15px 0 0'}} placeholder="请选择所属医院">
											{this.state.hospitalData && this.state.hospitalData.map(item => {
												return <Option key={item.id} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
											})}
										</Select>
										{/* showSearch 支持搜索功能；allowClear 支持清除; optionFilterProp 搜索过滤的值 */}
								床位费类型：<Select showSearch optionFilterProp="seatchprop" allowClear value={this.state.locDesc} onChange={this.onChangeLocDesc} onFocus={this.onFocusLocDesc} style={{width: '150px', margin: '23px 15px 0 0'}} placeholder="请选择科室名称">
											{this.state.DepartmentInformation && this.state.DepartmentInformation.map(item => {
												return <Option key={item.id} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
											})}
										</Select>
								医嘱项：<Select showSearch optionFilterProp="seatchprop" allowClear value={this.state.locType} onChange={this.onChangelocType} style={{width: '150px', margin: '23px 15px 0 0'}} placeholder="请选择科室类型">
											{this.state.selectData.locType && this.state.selectData.locType.map(item => {
												return <Option key={item.id} value={item.code} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
											})}
										</Select>
								<Button onClick={this.handleQuery} style={{ margin: '23px 15px 20px 0', background: 'rgba(255,255,255,1)'}}>查询</Button>
							</Col>
							<Col span={6} style={{ textAlign: 'right' }}>
								<Button icon="plus" onClick={this.handleAdd} style={{ background: 'rgba(247,128,93,1)', color: '#fff', margin: '23px 15px 0 0' }}>新科室</Button>
								<Button icon="import" onClick={this.handleLibraryImport} style={{margin: '23px 15px 0 0'}}>公共库导入</Button>
							</Col>
						</Row>
					</div>
					<div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
					<div style={{ padding: 24 }} className="table-body-height">
						{/* handelThis将夫组件的属性与方法给子组件访问 */}
						<PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} />
					</div>
					{/* 导入科室 */}
					<CommonLibraryImport onRef={this.libraryOnRef} selectData={this.state.selectData} hospitalData={this.state.hospitalData} />
				</div>
			</Spin>
		)
	}
}

